package com.xingdata.jjxc.activity.viewdata;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.InfoWindowAdapter;
import com.amap.api.maps.AMap.OnInfoWindowClickListener;
import com.amap.api.maps.AMap.OnMapClickListener;
import com.amap.api.maps.AMap.OnMarkerClickListener;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.navi.AMapNavi;
import com.amap.api.navi.AMapNaviListener;
import com.amap.api.navi.enums.NaviType;
import com.amap.api.navi.enums.PathPlanningStrategy;
import com.amap.api.navi.model.AMapLaneInfo;
import com.amap.api.navi.model.AMapNaviCross;
import com.amap.api.navi.model.AMapNaviInfo;
import com.amap.api.navi.model.AMapNaviLocation;
import com.amap.api.navi.model.AMapNaviPath;
import com.amap.api.navi.model.AMapNaviTrafficFacilityInfo;
import com.amap.api.navi.model.AMapTrafficStatus;
import com.amap.api.navi.model.AimLessModeCongestionInfo;
import com.amap.api.navi.model.AimLessModeStat;
import com.amap.api.navi.model.NaviInfo;
import com.amap.api.navi.model.NaviLatLng;
import com.amap.api.navi.view.RouteOverLay;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.GeocodeSearch.OnGeocodeSearchListener;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.poisearch.PoiSearch.OnPoiSearchListener;
import com.amap.api.services.weather.LocalWeatherForecastResult;
import com.amap.api.services.weather.LocalWeatherLive;
import com.amap.api.services.weather.LocalWeatherLiveResult;
import com.amap.api.services.weather.WeatherSearch;
import com.amap.api.services.weather.WeatherSearch.OnWeatherSearchListener;
import com.amap.api.services.weather.WeatherSearchQuery;
import com.autonavi.tbt.NaviStaticInfo;
import com.autonavi.tbt.TrafficFacilityInfo;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.loopj.android.http.RangeFileAsyncHttpResponseHandler;
import com.xingdata.jjxc.App;
import com.xingdata.jjxc.BuildConfig;
import com.xingdata.jjxc.ComEntity;
import com.xingdata.jjxc.Common;
import com.xingdata.jjxc.R;
import com.xingdata.jjxc.RequestCode;
import com.xingdata.jjxc.activity.AddWayPointsActivity;
import com.xingdata.jjxc.activity.NaviCompactActivity;
import com.xingdata.jjxc.activity.NaviSerchActivity;
import com.xingdata.jjxc.activity.NaviStatusViewActivity;
import com.xingdata.jjxc.activity.SettingsActivity;
import com.xingdata.jjxc.ar_navi.ARHudComm;
import com.xingdata.jjxc.ar_navi.AR_Navi;
import com.xingdata.jjxc.ar_navi.ByteUtil;
import com.xingdata.jjxc.ar_navi.LocationAdapter;
import com.xingdata.jjxc.ar_navi.NaviUpdateInfo;
import com.xingdata.jjxc.ar_navi.ProtoMsg;
import com.xingdata.jjxc.ar_navi.TrafficStatusUpdateData;
import com.xingdata.jjxc.enty.ComAddressEntity;
import com.xingdata.jjxc.enty.FindAllEntity;
import com.xingdata.jjxc.enty.HUDParameterEntity;
import com.xingdata.jjxc.enty.NaviHistoryEntity;
import com.xingdata.jjxc.enty.RespEntity;
import com.xingdata.jjxc.favorites.FavoritesEntity;
import com.xingdata.jjxc.http.HttpResponseListener;
import com.xingdata.jjxc.http.HttpUtil;
import com.xingdata.jjxc.m.avt.ComAddressSetavt;
import com.xingdata.jjxc.map.navi.IATController;
import com.xingdata.jjxc.map.navi.TTSController;
import com.xingdata.jjxc.map.navi.activity.SimpleNaviActivity;
import com.xingdata.jjxc.map.navi.activity.SystemTools;
import com.xingdata.jjxc.map.navi.activity.util.Utils;
import com.xingdata.jjxc.pushnavi.NaviParams;
import com.xingdata.jjxc.utils.Constants;
import com.xingdata.jjxc.utils.JUtils;
import com.xingdata.jjxc.utils.JsonParser;
import com.xingdata.jjxc.utils.Log;
import com.xingdata.jjxc.utils.SharedPreTools;
import com.xingdata.jjxc.utils.StringUtil;
import com.xingdata.jjxc.utils.SystemInfo;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import jar.MessageManager;
import jar.model.RequestEntity;
import jar.tools.InstructionSet;
import jar.tools.UdpTools;

/**
 * 
 * @Description: TODO(导航页面)
 * @date 2015-9-8 下午5:55:22 Creater JiangMin
 */
public class NaviViewData implements LocationSource, AMapLocationListener, OnMapClickListener, OnGeocodeSearchListener,
		TextWatcher, OnItemClickListener, OnMarkerClickListener, OnClickListener, OnInfoWindowClickListener,
		InfoWindowAdapter, AMapNaviListener, OnPoiSearchListener, OnWeatherSearchListener, android.widget.RadioGroup.OnCheckedChangeListener {
	private String TAG = "NaviViewData";
	private AMap aMap;
	private MapView mapView;
	private TTSController ttsManager;
	// 搜索框
	private EditText serchEditText;
	// 搜索重新封装的数据
	// private List<Tip> tips = new ArrayList<Tip>();
	private View pop_view;
	// 驾车路径规划起点，途经点，终点的list
	private List<NaviLatLng> mStartPointList = new ArrayList<NaviLatLng>();
	private List<NaviLatLng> mEndPointList = new ArrayList<NaviLatLng>();
	private List<NaviLatLng> mWayPointsList = new ArrayList<NaviLatLng>();
	// 记录起点、终点、途经点位置
	private NaviLatLng mStartPoint = new NaviLatLng();
	private NaviLatLng mEndPoint = new NaviLatLng();

	private Marker mEndMarker;
	private PopupWindow navigationPopupWindow = null;
	private PopupWindow routeChooseView = null;
	// 坐标/地名转换
	private GeocodeSearch geocoderSearch;
	/** 记录地图点击事件相应情况，根据选择不同，地图响应不同 private int mMapClickMode = MAP_CLICK_NO; */
	private int mMapClickMode = MAP_CLICK_NO;
	/** 地图不接受点击事件private static final int MAP_CLICK_NO = 0; */
	private static final int MAP_CLICK_NO = 0;
	/** 地图点击设置终点private static final int MAP_CLICK_END = 3; */
	private static final int MAP_CLICK_END = 3;
	// 规划线路
	private RouteOverLay mRouteOverLay;
	// // 是否驾车和是否计算成功的标志
	private boolean mIsDriveMode = true;
	private boolean mIsCalculateRouteSuccess = false;
	private AMapNavi mAMapNavi;
    private boolean isNavigating = false;
	private List<String> aMapNaviGuides = null;
	// 是否真实导航 true模拟导航
	private Boolean isNaviRote = true;
	/**地名*/
	private String strPlaceName = "";
	/**地址*/
	private String strPlaceAddress = "";
	/**距离*/
	private String strPlaceDistance = "";
	/** infoWindo是否出现 */
	private boolean isGetInfoWindow = false;
	/** 判断是从哪里进来的 0 导航收藏添加 1 常用地址导航 2导航 */
	private int inNaviLocionType = 2;
	private ComAddressEntity mAddressEntity = null;
	// 总路长
	private String strAllLength;
	private Boolean isCalculateSuccess = false;
	private int IatrequestCode = 2;
	
	private Boolean isBack = true;
	private PoiSearch.Query query;// Poi查询条件类
	private PoiSearch poiSearch;// POI搜索
	/**poi返回的结果*/
	private PoiResult poiResult; 

	private View tabView;
	private Handler mHandler;
	private Activity mContext;
	private Bundle savedInstanceState;

	// 默认规划路线方案
	private int inCalculateRouteType = AMapNavi.DrivingFastestTime;
	private OnLocationChangedListener mListener;
		/* 高德Android定位sdk */
	/**声明AMapLocationClient对象*/
	private AMapLocationClient mlocationClient = null;
	/**声明AMapLocationClientOption对象*/
	private AMapLocationClientOption mLocationOption = null;
	private WeatherSearchQuery mquery;
	private WeatherSearch mweathersearch;
	private TextView temperatureTextView, weatherTextView;
	private boolean isCenter = false;
	private CheckBox navi_setup;
	private RadioButton naviSet_shortest_time, naviSet_avoiding_jams, naviSet_avoidind_charges;
	/** 添加收藏五角心 */
	private ImageView collect_iv;
	
	/** 导航设置rg*/
	private RadioGroup navi_setup_rg;
	/** 设置界面出现和隐藏逻辑控制 */
	// private boolean isShow_navi_setup_boolean = false;
	/** 导航POI信息窗口infowindow */
	private LinearLayout navi_infowindow_rl;
	/** infoWindow设置地名 */
	private TextView navi_place_name;
	/** infoWindow设置地名 */
	private TextView navi_place_address;
	/**infoWindow设置距离*/
	private TextView navi_place_distance;
	/** 开始导航 */
	private LinearLayout navi_startGuide_ll;
    private TextView   tv_navi_status;
		/* 语音 */
	/** 语音按钮 */
	private ImageView speech_navi_iv;
	/** 语音控件 */
	private IATController iatController;

	private ImageView setting_navi;
	private ImageView navi_go;

	private TextView my_location;

		/* 导航收藏夹 */
	/**
	 * 一个HashMap值private HashMap<String, String> paramsMap = new HashMap<String,
	 * String>();
	 */
	private HashMap<String, String> paramsMap = new HashMap<String, String>();

	/**收藏夹实体*/
	private FavoritesEntity favoritesEntity = new FavoritesEntity();
	
	/** 收藏夹实体列表 */
	private List<FavoritesEntity> favoritesEntityList = new ArrayList<FavoritesEntity>();
	
	/** 收藏成功返回id*/
	private String collectId;

	/** 找到所有数据private List<FindAllEntity> findAllEntlist; */
	private List<FindAllEntity> findAllEntlist;

	private FindAllEntity mFindAllEntity;
	
	private HttpUtil mHttpUtil = null;
	
	boolean isCollectedChecked = false;
	
	boolean isRouting = false;
	/** 3个方案布局 */
	private RelativeLayout re;
	LinearLayout mainLinear;
	//算路完成所有的视图定义
	private TextView roadToll;
	private TextView lightsCount;
	private TextView line_one;
	private TextView time_shortest_one;
	private TextView time_one;
	private TextView distance_one;
	private TextView line_two;
	private TextView time_shortest_two;
	private TextView time_two;
	private TextView distance_two;
	private TextView line_three;
	private TextView time_shortest_three;
	private TextView time_three;
	private TextView distance_three;

	public NaviViewData(View tabView, Activity mContext, Handler mHandler, Bundle savedInstanceState,
			RelativeLayout re,LinearLayout linear) {
		this.tabView = tabView;
		this.mHandler = mHandler;
		this.mContext = mContext;
		this.savedInstanceState = savedInstanceState;
		this.re = re;
		this.mainLinear = linear;
		initView();
		EventBus.getDefault().register(this);
	}

	private void initView() {
		
		// /*
		// * 设置离线地图存储目录，在下载离线地图或初始化地图设置; 使用过程中可自行设置, 若自行设置了离线地图存储的路径，
		// * 则需要在离线地图下载和使用地图页面都进行路径设置
		// */
		// // Demo中为了其他界面可以使用下载的离线地图，使用默认位置存储，屏蔽了自定义设置
		// MapsInitializer.sdcardDir =SDCardTools
		// .getFilePath(SDCardTools.OFFLINE_MAP);
		mHttpUtil = HttpUtil.getInstance(mContext);
		
		// 设置字体
		Typeface font = Typeface.createFromAsset(mContext.getAssets(), JUtils.TypefacePath);
		((TextView) tabView.findViewById(R.id.navi_title_city)).setTypeface(font);
		((TextView) tabView.findViewById(R.id.navi_weather)).setTypeface(font);
		((TextView) tabView.findViewById(R.id.navi_temperature)).setTypeface(font);
		((TextView) tabView.findViewById(R.id.tv_trafficRestriction)).setTypeface(font);
		((TextView) tabView.findViewById(R.id.tv_trafficRestrictionNum)).setTypeface(font);
		((TextView) tabView.findViewById(R.id.com_search_map_et)).setTypeface(font);
		
		((RadioButton) tabView.findViewById(R.id.naviSet_shortest_time)).setTypeface(font);
		((RadioButton) tabView.findViewById(R.id.naviSet_avoiding_jams)).setTypeface(font);
		((RadioButton) tabView.findViewById(R.id.naviSet_avoidind_charges)).setTypeface(font);

		my_location = (TextView) tabView.findViewById(R.id.my_location);

		serchEditText = (EditText) tabView.findViewById(R.id.com_search_map_et);
		serchEditText.setOnClickListener(this);

		speech_navi_iv = ((ImageView) tabView.findViewById(R.id.speech_navi_iv));
		speech_navi_iv.setOnClickListener(this);

		temperatureTextView = (TextView) tabView.findViewById(R.id.navi_temperature);
		weatherTextView = (TextView) tabView.findViewById(R.id.navi_weather);
        
		// 导航设置按钮
		navi_setup = (CheckBox) tabView.findViewById(R.id.navi_setup);
		navi_setup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean isShow) {
				// TODO Auto-generated method stub
				if (isShow) {
					// isShow=true 先跑true
					Log.d(TAG, "isSHow1" + isShow);
					navi_setup_rg.setVisibility(View.VISIBLE);
				} else {
					Log.d(TAG, "isSHow2" + isShow);
					// isShow=false
					navi_setup_rg.setVisibility(View.GONE);
				}

			}
		});
        tv_navi_status = (TextView)tabView.findViewById(R.id.txt_navi_status);// 导航状态
        tv_navi_status.setText(isNavigating?"停止导航":"开始导航");

		navi_setup_rg = (RadioGroup) tabView.findViewById(R.id.navi_setup_rg);
		navi_setup_rg.setOnCheckedChangeListener(this);

		navi_place_name = (TextView) tabView.findViewById(R.id.navi_place_name);
		
		navi_place_address = (TextView) tabView.findViewById(R.id.navi_place_address);
		
		navi_place_distance = (TextView)tabView.findViewById(R.id.navi_place_distance);

		navi_startGuide_ll = (LinearLayout) tabView.findViewById(R.id.navi_startGuide_ll);
		navi_startGuide_ll.setOnClickListener(this);
		
		//算路完成后视图的初始化
		roadToll = (TextView)re.findViewById(R.id.road_toll);
		lightsCount = (TextView)re.findViewById(R.id.lights_count);
		line_one = (TextView)re.findViewById(R.id.line_one);
		time_shortest_one = (TextView)re.findViewById(R.id.time_shortest_one);
		time_one = (TextView)re.findViewById(R.id.time_one);
		distance_one = (TextView)re.findViewById(R.id.distance_one);
		line_two = (TextView)re.findViewById(R.id.line_two);
		time_shortest_two = (TextView)re.findViewById(R.id.time_shortest_two);
		time_two = (TextView)re.findViewById(R.id.time_two);
		distance_two = (TextView)re.findViewById(R.id.distance_two);
		line_three = (TextView)re.findViewById(R.id.line_three);
		time_shortest_three = (TextView)re.findViewById(R.id.time_shortest_three);
		time_three = (TextView)re.findViewById(R.id.time_three);
		distance_three = (TextView)re.findViewById(R.id.distance_three);	
		re.findViewById(R.id.routeNavi).setOnClickListener(this);
		re.findViewById(R.id.time_shortest).setOnClickListener(this);
		re.findViewById(R.id.distance_shortest).setOnClickListener(this);
		re.findViewById(R.id.methord_three).setOnClickListener(this);
		re.findViewById(R.id.add_way_points).setOnClickListener(this);
		
		/** 收藏功能 */
		collect_iv = (ImageView) tabView.findViewById(R.id.collect_iv);
		collect_iv.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if (isCollectedChecked==false) {
					Log.d(TAG, "收藏="+isCollectedChecked);
					favoritesEntity.setPlace_name(strPlaceName);
					favoritesEntity.setPlace_address(strPlaceAddress);
					favoritesEntity.setPlace_lng(mEndPoint.getLongitude()+"");
					favoritesEntity.setPlace_lng(mEndPoint.getLatitude()+"");
					doPost_addCollection();
					
					collect_iv.setImageResource(R.drawable.icon_collect_info_pressed);
					isCollectedChecked=true;
				}else {
					Log.d(TAG, "取消收藏="+isCollectedChecked);
					doPost_cancelCollection();
					collect_iv.setImageResource(R.drawable.icon_collect_info);
					isCollectedChecked=false;
				}
			}
		});

		setting_navi = (ImageView) tabView.findViewById(R.id.setting_navi);
		setting_navi.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				Intent intent = new Intent(mContext, SettingsActivity.class);
				mContext.startActivity(intent);
			}
		});

		navi_go = (ImageView) tabView.findViewById(R.id.navi_nav_go);
		navi_go.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				Bundle bundle = new Bundle();
				bundle.putString("name",currPos.getPlace_name());
				bundle.putString("address",currPos.getPlace_address());
				bundle.putString("lat",currPos.getPlace_lat());
				bundle.putString("lng",currPos.getPlace_lng());
				Intent intent = new Intent(mContext, NaviCompactActivity.class);
				intent.putExtras(bundle);
				mContext.startActivityForResult(intent,RequestCode.REQUESTCODE_NAVI_DS3);
			}
		});


		navi_infowindow_rl = (LinearLayout) tabView.findViewById(R.id.navi_infowindow_rl);

		// 地图初始化
		mapView = (MapView) tabView.findViewById(R.id.map);
		mapView.onCreate(savedInstanceState);
		if (aMap == null) {
			aMap = mapView.getMap();
			setUpMap();
		}

		mMapClickMode = MAP_CLICK_END;
		mAMapNavi = AMapNavi.getInstance(App.instance.mainActivity);
		mAMapNavi.addAMapNaviListener(this);
		aMap.setOnInfoWindowClickListener(this);
		aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式

		geocoderSearch = new GeocodeSearch(mContext);

		// 输入提示的监听接口
		// serchEditText.addTextChangedListener(this);
		// serchEditText.setOnItemClickListener(this);
		// 地名搜索监听接口
		geocoderSearch.setOnGeocodeSearchListener(this);

		ttsManager = TTSController.getInstance(mContext);// 初始化语音模块
		checkSpeaker();


		// 初始化语音接口
		initIATController(); 
		
	}

	private void checkSpeaker() {
		if (isEnableSpeaker()){
			openSpeaker();
		}else{
			closeSpeaker();
		}
	}

    public boolean isNavigating(){
        return isNavigating;
    }

	private boolean isEnableSpeaker(){
		int v = 1;
		try {
			String value = SharedPreTools.getString(mContext,"cof_navivoice","9");
			if(null != value && value.length()>0) {
				v = Integer.parseInt(value);
			}
		}catch(NumberFormatException ex){
			Log.e(TAG,"cof_navivoice="+SharedPreTools.getString(mContext,"cof_navivoice","1"));
			v = 9;
		}
		Log.i(TAG,"cof_navivoice="+v);
		return v != 0;
	}

	public void openSpeaker(){
		if(null != mAMapNavi)
			mAMapNavi.addAMapNaviListener(TTSController.getInstance(mContext));
	}
	public void closeSpeaker(){
		if(null != mAMapNavi)
			mAMapNavi.removeAMapNaviListener(TTSController.getInstance(mContext));
	}
	 
	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		// TODO Auto-generated method stub
		String key = null;
		key = Common.COF_NAVIPATHTYPE;
		com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
		int checkID = group.getCheckedRadioButtonId();
		if (checkID == -1) {
			return;
		}
		String strTag = group.findViewById(checkID).getTag().toString();
		jsonObject.put(key, strTag);
		MessageManager.send(Integer.parseInt(SystemInfo.getSendPORT()), new RequestEntity(jsonObject.toJSONString(),
				InstructionSet.INSTRUCTION_AUTH_OPTIONS_TO_HUD + ""));
		
	}

	/** 收藏地址到服务器*/
	private void doPost_addCollection() {
		
		paramsMap = new HashMap<String, String>();
		// 用户id
		paramsMap.put("user_id", SystemInfo.getUserInfo().getUserid());
		// 地名
		paramsMap.put("place_name", favoritesEntity.getPlace_name());
		// 地址
		paramsMap.put("place_address", favoritesEntity.getPlace_address());
		// 经度
		paramsMap.put("place_lng", mEndPoint.getLongitude() + "");
		// 纬度
		paramsMap.put("place_lat", mEndPoint.getLatitude() + "");
		
		mHttpUtil.Post(App.ZZD_REQUEST_ADDCOLLECTION, paramsMap, new HttpResponseListener() {

			@Override
			public void onSuccess(RespEntity respEntity) {
				Log.d(TAG, "收藏onSuccess.respEntity="+respEntity);
				collectId = respEntity.getResult();;
				Log.d(TAG, "collectId="+collectId);
			}

			@Override
			public void onLoading(int vurrent) {
				// TODO Auto-generated method stub
				Log.d(TAG, "收藏中="+vurrent);
			}

			@Override
			public void onFailure(String result) {
				// TODO Auto-generated method stub
				Log.d(TAG, "收藏.onFailure.result="+result);
			}
		});
	}
	
	/**从MainActivity获取favoritesEntity值设置id，用于取消收藏*/
	public void getCollect_id(String collect_id){
		favoritesEntity.setCollect_Id(collect_id);
		collect_iv.setImageResource(R.drawable.icon_collect_info_pressed);
		isCollectedChecked = true;
	}
	
	/** 取消收藏地址到服务器*/
	private void doPost_cancelCollection() {
		paramsMap = new HashMap<String, String>();
		Log.d(TAG, "collectId="+favoritesEntity.getCollect_Id());
		// 用户id
		paramsMap.put("collect_id", favoritesEntity.getCollect_Id());

		mHttpUtil.Post(App.ZZD_REQUEST_CANCELCOLLECTION, paramsMap, new HttpResponseListener() {

			@Override
			public void onSuccess(RespEntity respEntity) {
				// TODO Auto-generated method stub
				 Log.d(TAG, "取消收藏onSuccess.respEntity="+respEntity);
			}

			@Override
			public void onLoading(int vurrent) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onFailure(String result) {
				// TODO Auto-generated method stub
				Log.d(TAG, "取消收藏onFailure.result="+result);
			}
		});
	}
	
	/** 向服务器发送消息，获取收藏夹地址 */
	private void doGet_findCollectionsbyUserid() {
		paramsMap = new HashMap<String, String>();
		// 用户id
		paramsMap.put("user_id", SystemInfo.getUserInfo().getUserid());

		mHttpUtil.Post(App.ZZD_REQUEST_FINDCOLLECTIONSBYUSERID, paramsMap, new HttpResponseListener() {

			@Override
			public void onSuccess(RespEntity respEntity) {
				// TODO Auto-generated method stub
//				favoritesEntityList.addAll(JSON.parseArray(respEntity.getResult(), FavoritesEntity.class));
			}

			@Override
			public void onLoading(int vurrent) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onFailure(String result) {
				// TODO Auto-generated method stub

			}
		});
	}

	/** 显示导航信息窗口，主要是为了在MainActivity引用bundle.getSerializable(”poi“)的时候显示用 */
	public void showInfoWindow() {
		navi_infowindow_rl.setVisibility(View.VISIBLE);
		navi_place_name.setText(strPlaceName);
		navi_place_address.setText(strPlaceAddress);
		navi_place_distance.setText(strPlaceDistance);
	}

	@Override
	public void onClick(View v) {

		mIsCalculateRouteSuccess = false;
		isCalculateSuccess = false;
		mIsDriveMode = true;
		switch (v.getId()) {

		case R.id.pop_layout:
			navigationPopupWindow.dismiss();
			break;
		// 开始导航
		case R.id.pop_begin: 
			//先屏蔽弹出提示框“是否继续使用HUD导航”  2016.9.19 by ly
			showKeylessDialog();

			//发送导航信息到s3  2016.9.19 by ly
//			if(App.isS3Pruduct){
//				NaviParams param = new NaviParams();
//				param.selectedIndex = 0;
//				if (mStartPoint != null && mEndPoint != null) {
//					param.start = new MyLatLng(mStartPoint.getLatitude(),
//							mEndPoint.getLongitude());
//					param.dest = new MyLatLng(mEndPoint.getLatitude(),
//							mEndPoint.getLongitude());
//					if (mWayPointsList.size() > 0) {
//						for (int i = 0; i < mWayPointsList.size(); i++) {
//							MyLatLng myLatLng = new MyLatLng(mWayPointsList
//									.get(i).getLatitude(), mWayPointsList
//									.get(i).getLongitude());
//							param.waypoints.add(myLatLng);
//						}
//					}
//					param.useGps = false;
//					ProtoMsg msg = new ProtoMsg("startNavi", param.toJsonString());
//					Log.e(TAG,"发送导航数据："+param.toJsonString());
////					UdpClient.msgQueue.add(msg);
//					MessageManager.send(Integer.parseInt(SystemInfo.getSendPORT()),Gson.,
//							InstructionSet.INSTRUCTION_AUTH_OPTIONS_TO_HUD + ""));
//				}
//			}
			break;
		// 手机导航
		case R.id.pop_startNavi_byPhone:
			Log.d(TAG, "跳转到手机导航界面");
			// ((Activity)mContext).startActivity(new Intent(mContext,
			// GPSNaviActivity.class));
			break;
		case R.id.stop:
			MessageManager.send(Integer.parseInt(SystemInfo.getSendPORT()), new RequestEntity("",
					InstructionSet.INSTRUCTION_AUTH_NAVI_STOP_HUD_TO_HUD + ""));
 
			if (navigationPopupWindow != null && navigationPopupWindow.isShowing()) {
				navigationPopupWindow.dismiss();
			}
			break;
		// 模拟
		case R.id.pop_simulate:
			showKeylessDialog();
			if (UdpTools.isContent) {
				isNaviRote = true;
				calculateDriveRoute("1");
			}
			break;
		// 返回按钮监听
		case R.id.icon_iv:
			((Activity) mContext).finish();
			break;
		// 语音按钮
		case R.id.speech_navi_iv:
			iatController.start();
			Log.d(TAG, "语音button is cliked!");
			break;
		case R.id.goBack:
			((Activity) mContext).finish();
			break;

		// case R.id.seachButton:
		// String strSerach = serchEditText.getText().toString().trim();
		// if (strSerach.length() == 0) {
		// Log.e(TAG, "搜索框内容不能为空！");
		// return;
		// }
		// doSearchQuery(strSerach);
		// break;

		// 搜索输入框监听
		case R.id.com_search_map_et:
			Intent intent = new Intent();
			intent.setClass(mContext, NaviSerchActivity.class);
			/* 请求活动的时候，接收返回数据的onActivityResult写在了MainActivity里面 */
			((Activity) mContext).startActivityForResult(intent, RequestCode.REQUESTCODE_NAVI);
			break;

		// 开始导航
		case R.id.navi_startGuide_ll:
			Log.d(TAG, "navi_startGuide_ll");
            if(isNavigating){
                showNaviStopDialog();
                return;
            }
			if (inNaviLocionType != Constants.inNaviLocionType_COLLECTION) {
				showPOP2();
			} else {
				Intent emulatorIntent = new Intent(mContext, ComAddressSetavt.class);
				
				Bundle bundle = new Bundle();
				bundle.putString("areaid", serchEditText.getText().toString());// 地区
				bundle.putString("address", strPlaceName);// 实际地址
				bundle.putString("longitude", mEndPoint.getLongitude() + "");
				bundle.putString("latitude", mEndPoint.getLatitude() + "");
				emulatorIntent.putExtras(bundle);
				((Activity) mContext).startActivity(emulatorIntent);
				((Activity) mContext).finish();
			}

			break;
		case R.id.routeNavi:
//			showChooseNavi();
            if(isNavigating){
                // Popup StopNavi window
            }else{
                showNavSelectDialog();// lxs 导航方式选择
            }
			break;
		case R.id.time_shortest:
			seletedRoutePath = 0;
			chooseRouteType();
			break;
		case R.id.distance_shortest:
			seletedRoutePath = 1;
			chooseRouteType();
			break;
		case R.id.methord_three:
			seletedRoutePath = 2;
			chooseRouteType();
			break;
		case R.id.add_way_points:
			//跳到添加途经点界面
			Intent addPointIntent = new Intent(mContext,AddWayPointsActivity.class);
			mContext.startActivity(addPointIntent);
			break;
		default:
			break;
		}

	}
    // lxs 导航方式选择
	private void showNavSelectDialog() {
        if(!ARHudComm.getInstance().isNavi_data_debug_mode()){
            // 判断设备是否连接，没有连接则无法导航
            if(!ARHudComm.getInstance().deviceIsConnected()){
                showKeylessDialog();
                return;
            }
        }

		final Dialog exitDialog = new Dialog(mContext, R.style.my_dialog);
		View v = LayoutInflater.from(mContext).inflate(R.layout.dialog_start_new_navigation, null);
		v.findViewById(R.id.dialog_btn_gps_navi).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				exitDialog.dismiss();
                mAMapNavi.stopNavi();

				if(!App.deviceSettings.onBoardNavi){
					// lxs--------- 发送导航路径信息
					ARHudComm.getInstance().sendToAR(AR_Navi.sendRefPoint(mStartPoint.getLatitude(),
							mStartPoint.getLongitude()));
					ARHudComm.getInstance().sendToAR(AR_Navi.sendRouteInfoToAR(mStartPoint,mAMapNavi));
					currentNaviPath = mAMapNavi.getNaviPaths().get(seletedRoutePath);

					updateCurrentTrafficStatusData();// 更新交通道路信息
				}

				mAMapNavi.startNavi(NaviType.GPS);
				endCalculate();

				if(App.deviceSettings.onBoardNavi){// 车载导航模式的导航参数
					//send naviParam to device for onBoardNavi
					NaviParams naviParams = new NaviParams();
					naviParams.start = mStartPoint;
					naviParams.end = mEndPoint;
					naviParams.waypoints = mWayPointsList;
                    naviParams.naviPathSeletedIndex = seletedRoutePath;
                    naviParams.currentStragtegyForNavi = currentStragtegyForNavi;
					naviParams.useGps = true;
					ProtoMsg request = new ProtoMsg("start_on_board_navi",naviParams.toJsonString());
					ARHudComm.getInstance().sendToHud(request.toBytes());
				}
				startNaviViewInfoActivity();
			}
		});

		v.findViewById(R.id.dialog_btn_emulate_navi).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				exitDialog.dismiss();
                mAMapNavi.stopNavi();

				if(!App.deviceSettings.onBoardNavi) {
					ARHudComm.getInstance().sendToAR(AR_Navi.sendRefPoint(mStartPoint.getLatitude(),
							mStartPoint.getLongitude()));
					// lxs--------- 发送导航路径信息
					ARHudComm.getInstance().sendToAR(AR_Navi.sendRouteInfoToAR(mStartPoint, mAMapNavi));
					currentNaviPath = mAMapNavi.getNaviPaths().get(seletedRoutePath);

					updateCurrentTrafficStatusData();// 更新交通道路信息
				}

				mAMapNavi.startNavi(NaviType.EMULATOR);
				mAMapNavi.setEmulatorNaviSpeed(150);
				endCalculate();

				if(App.deviceSettings.onBoardNavi){// 车载导航模式的导航参数
					//send naviParam to device for onBoardNavi
					NaviParams naviParams = new NaviParams();
					naviParams.start = mStartPoint;
					naviParams.end = mEndPoint;
					naviParams.waypoints = mWayPointsList;
                    naviParams.naviPathSeletedIndex = seletedRoutePath;
                    naviParams.currentStragtegyForNavi = currentStragtegyForNavi;
					naviParams.useGps = false;
					ProtoMsg request = new ProtoMsg("start_on_board_navi",naviParams.toJsonString());
					ARHudComm.getInstance().sendToHud(request.toBytes());
				}

				startNaviViewInfoActivity();
			}
		});
		LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		exitDialog.addContentView(v, params);
		exitDialog.show();
	}

	void startNaviViewInfoActivity(){
		Intent intent =new Intent(mContext, NaviStatusViewActivity.class);
		Bundle extra = new Bundle();
		extra.putString("dest_place_name",strPlaceName);
		extra.putString("dest_address",strPlaceAddress);
		extra.putString("dest_distance",strPlaceDistance);
		intent.putExtra("data",extra);
		mContext.startActivity(intent);
	}

	private void showKeylessDialog() {
        // lxs 设备是否连接
		final Dialog exitDialog = new Dialog(mContext, R.style.my_dialog);
		View v = LayoutInflater.from(mContext).inflate(R.layout.dialog_device, null);
		if (isNavigating) {
			((TextView) v.findViewById(R.id.dialog_text)).setText("正在进行导航...");
		} else {
			((TextView) v.findViewById(R.id.dialog_text)).setText("手机未连接设备!");
		}

		v.findViewById(R.id.dialog_cancel).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				exitDialog.dismiss();
			}
		});
		v.findViewById(R.id.dialog_continue).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				exitDialog.dismiss();
				endCalculate();
			}
		});
		LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		exitDialog.addContentView(v, params);
		exitDialog.show();
	}

    // 是否取消当前导航
    private void showNaviStopDialog() {
        // lxs 设备是否连接
        final Dialog exitDialog = new Dialog(mContext, R.style.my_dialog);
        View v = LayoutInflater.from(mContext).inflate(R.layout.dialog_stop_current_navigation, null);
        v.findViewById(R.id.dialog_cancel).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                exitDialog.dismiss();
            }
        });
        v.findViewById(R.id.dialog_confirm).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                mAMapNavi.stopNavi();
                isNavigating = false;
                ttsManager.playText("正在为您停止当前导航");
                tv_navi_status.setText("开始导航");
                exitDialog.dismiss();
            }
        });
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        exitDialog.addContentView(v, params);
        exitDialog.show();
    }

	/** 初始化语音接口 */
	private void initIATController() {
		iatController = IATController.getInstance((Activity) mContext, recognizerDialogListener);
	}

	private void setUpMap() {
		aMap.setLocationSource(this);// 设置定位监听
		aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
		aMap.getUiSettings().setZoomControlsEnabled(false);// 控制缩放控件显示和隐藏（false隐藏缩放控件）
		aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
		// 设置定位的类型为定位模式：定位（AMap.LOCATION_TYPE_LOCATE）、跟随（AMap.LOCATION_TYPE_MAP_FOLLOW）
		// 地图根据面向方向旋转（AMap.LOCATION_TYPE_MAP_ROTATE）三种模式
		// type - 定位的类型。提供3种类型，分别为：LOCATION_TYPE_LOCATE
		// 表示只在第一次定位移动到地图中心点，值为1；LOCATION_TYPE_MAP_FOLLOW 表示定位、移动到地图中心点并跟随，值为2和
		// LOCATION_TYPE_MAP_ROTATE 表示定位、移动到地图中心点，跟踪并根据方向旋转地图，值为3。
		if (inNaviLocionType != Constants.inNaviLocionType_COMMON) {
			aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_FOLLOW);
		}

		aMap.setOnMapClickListener(this);
		aMap.setMapType(SystemTools.isNight() ? AMap.MAP_TYPE_NIGHT : AMap.MAP_TYPE_NORMAL);
		aMap.setOnMarkerClickListener(this);
		aMap.setOnInfoWindowClickListener(this);
		aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式
	}

	@Override
	public void onPoiSearched(PoiResult result, int rCode) {

		strPlaceName = "";
		if (rCode == 0) {
			Log.d(TAG, "POI搜索成功_onPoiSearched");
			if (result != null && result.getQuery() != null) {// 搜索poi的结果
				if (result.getQuery().equals(query)) {// 是否是同一条
					poiResult = result;
					// 取得搜索到的poiitems有多少页
					List<PoiItem> poiItemList = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
					List<SuggestionCity> suggestionCityList = poiResult.getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息
					
					if (poiItemList != null && poiItemList.size() > 0) {
						Intent intent = new Intent(mContext, NaviSerchActivity.class);
						Bundle bundle = new Bundle();
						ArrayList<NaviHistoryEntity> historyEntities = new ArrayList<NaviHistoryEntity>();
						NaviHistoryEntity naviHistoryEntity = null;
						
						for (int i = 0; i < poiItemList.size(); i++) {
							naviHistoryEntity = new NaviHistoryEntity();
							naviHistoryEntity.setloca_nickname(poiItemList.get(i).getTitle());
							naviHistoryEntity.setloca_lat(poiItemList.get(i).getLatLonPoint().getLatitude() + "");
							naviHistoryEntity.setloca_lng(poiItemList.get(i).getLatLonPoint().getLongitude() + "");
							naviHistoryEntity.setloca_address(poiItemList.get(i).getSnippet());
							historyEntities.add(naviHistoryEntity);
						}
						bundle.putString("setVisible", "visible");
//						bundle.putParcelableArrayList("poi", (ArrayList<? extends Parcelable>) historyEntities);
						intent.putExtras(bundle);
						/* 请求活动的时候，接收返回数据的onActivityResult写在了MainActivity里面 */
						((Activity) mContext).startActivityForResult(intent, RequestCode.REQUESTCODE_NAVI);
						isBack = false;
//						Bitmap bitmap = null;
//						int ii = bitmap.getByteCount();
						// aMap.clear();// 清理之前的图标
						// PoiOverlay poiOverlay = new PoiOverlay(aMap,
						// poiItems);
						// poiOverlay.removeFromMap();
						// poiOverlay.addToMap();
						// poiOverlay.zoomToSpan();
					} else if (suggestionCityList != null && suggestionCityList.size() > 0) {
						// showSuggestCity(suggestionCities);
						Log.e(TAG, "这里没有搜索到结果推荐...");
					} else {
						Log.i(TAG, ((Activity) mContext).getResources().getString(R.string.no_result).toString());
					}
				}
			} else {
				Log.i(TAG, ((Activity) mContext).getResources().getString(R.string.no_result).toString());

			}
		} else if (rCode == 27) {
			Log.i(TAG, ((Activity) mContext).getResources().getString(R.string.error_network).toString());
		} else if (rCode == 32) {
			Log.i(TAG, ((Activity) mContext).getResources().getString(R.string.error_key).toString());
		} else {
			Log.i(TAG, ((Activity) mContext).getResources().getString(R.string.error_other).toString());
		}

	}

	@Subscribe(threadMode = ThreadMode.MainThread)
	public void handleNaviEvent(NaviEvent event){
		if(event.id == NaviEvent.StopNavi){
			mAMapNavi.stopNavi();
			isNavigating = false;
			tv_navi_status.setText(isNavigating?"停止导航":"开始导航");

            if(App.deviceSettings.onBoardNavi){
                ProtoMsg request_stop_navi = new ProtoMsg("stop_on_board_navi","");
                ARHudComm.getInstance().sendToHud(request_stop_navi.toBytes());
            }
		}
	}

	@Override
	public void onArriveDestination() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onArrivedWayPoint(int arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onCalculateRouteFailure(int arg0) {
		Log.e(TAG,"路径规划失败");
		Toast.makeText(mContext, "路径规划失败, 请重新导航", Toast.LENGTH_LONG).show();

	}

	byte[] LatlngBytes(NaviLatLng latLng){
		ByteBuffer byteBuffer = ByteBuffer.allocate(8*2);
		byteBuffer.put(ByteUtil.getBytes( latLng.getLatitude()));
		byteBuffer.put(ByteUtil.getBytes( latLng.getLatitude()));
		return  byteBuffer.array();
	}

	void logNaviPathData(final AMapNavi aMapNavi){
		new Thread(new Runnable() {
			@Override
			public void run() {
				RandomAccessFile raf = null;
				try {
					raf = new RandomAccessFile("/sdcard/navi_route_list.dat","rwd");
					List<NaviLatLng> coordLs = aMapNavi.getNaviPath().getCoordList();
					for (int i = 0 ; i < coordLs.size() ; i ++){
						raf.write(LatlngBytes(coordLs.get(i)));
					}
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
				}finally {
					if(raf!=null) try {
						raf.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

	AMapNaviPath currentNaviPath;
	@Override
	public void onCalculateRouteSuccess() {

        if(recalculateForYaw){//偏航之后计算成功路径
            recalculateForYaw = false;
            final AMapNaviPath naviPath = mAMapNavi.getNaviPath();
			currentNaviPath = mAMapNavi.getNaviPath();
			logNaviPathData(mAMapNavi);// 记录数据到sdcard

            if(naviPath!=null){
                if(!App.deviceSettings.onBoardNavi){
                    Log.i(TAG,"------------------>偏航之后计算成功路径 --------> 发送到AR");
                    ARHudComm.getInstance().sendToAR(AR_Navi.sendRefPoint(mStartPoint.getLatitude(),
                            mStartPoint.getLongitude()));
                    ARHudComm.getInstance().sendToAR(AR_Navi.sendRouteInfoToAR(mStartPoint,mAMapNavi));
                    return;
                }
            }
        }

		Log.i(TAG,"单路径规划成功");
		AMapNaviPath naviPath = mAMapNavi.getNaviPath();
		if (naviPath == null || mAMapNavi.getNaviGuideList() == null) {
			return;
		}

		//模拟导航
//		NaviLatLng endLatLng = naviPath.getEndPoint();
//		HUDParameterEntity entity = new HUDParameterEntity();
//		new (naviPath, entity).start();
//		
//		NaviEntity naviEntity = new NaviEntity(endLatLng.getLatitude() + "", endLatLng.getLongitude() + "",
//				inCalculateRouteType + "");
//		MessageManager.send(Integer.parseInt(SystemInfo.getSendPORT()), new RequestEntity(
//				JSON.toJSONString(naviEntity), InstructionSet.INSTRUCTION_AUTH_GET_CARCORDER_TO_HUD + ""));
//		Log.i(TAG, "目的地" + endLatLng.getLatitude() + "*" + endLatLng.getLongitude());
        //

	}

	private int seletedRoutePath = 0;
	//选择路线规划方案
	private void chooseRouteType() {
		//点击其他路线时显示花费和红绿灯总数
		Log.i(TAG,"[chooseRouteType] begin:path="+naviPaths.size());
		if(null == pathIds || pathIds.length-1<seletedRoutePath){
			Log.e(TAG,"[chooseRouteType] pathIds 错误");
			return;
		}
		if(null == naviPaths || null == naviPaths.get(pathIds[seletedRoutePath])){
			Log.e(TAG,"[chooseRouteType] naviPaths 错误");
			return;
		}

		roadToll.setText(String.valueOf(naviPaths.get(pathIds[seletedRoutePath]).getTollCost()));
		int lights = 0;
		for(int i = 0;i<naviPaths.get(pathIds[seletedRoutePath]).getStepsCount();i++){
			lights = lights+naviPaths.get(pathIds[seletedRoutePath]).getSteps().get(i).getTrafficLightNumber();
		}

		lightsCount.setText(" 元    红绿灯 "+String.valueOf(lights)+" 个");
		List<TextView> list = new ArrayList<TextView>(Arrays.asList(line_one,
				time_shortest_one, time_one, distance_one, line_two,
				time_shortest_two, time_two, distance_two, line_three,
				time_shortest_three, time_three, distance_three));
		for (int i = 1; i < 4; i++) {
			list.get(4 * seletedRoutePath + i).setTextColor(mContext.getResources().getColor(R.color.calculate_text_blue));
		}
		switch (seletedRoutePath) {
		case 0:
			list.get(0).setBackgroundColor(
					mContext.getResources().getColor(
							R.color.calculate_text_blue));
			list.get(4).setBackgroundColor(
					mContext.getResources().getColor(
							R.color.calculate_background));
			list.get(8).setBackgroundColor(
					mContext.getResources().getColor(
							R.color.calculate_background));
			list.get(6).setTextColor(
					mContext.getResources().getColor(
							R.color.calculate_notselected));
			list.get(10).setTextColor(
					mContext.getResources().getColor(
							R.color.calculate_notselected));
			for (int i = 5; i < 12; i = i + 2) {
				list.get(i).setTextColor(
						mContext.getResources().getColor(
								R.color.calculate_notselecteddeep));
			}
			break;
		case 1:
			list.get(4).setBackgroundColor(
					mContext.getResources().getColor(
							R.color.calculate_text_blue));
			list.get(0).setBackgroundColor(
					mContext.getResources().getColor(
							R.color.calculate_background));
			list.get(8).setBackgroundColor(
					mContext.getResources().getColor(
							R.color.calculate_background));
			list.get(2).setTextColor(
					mContext.getResources().getColor(
							R.color.calculate_notselected));
			list.get(10).setTextColor(
					mContext.getResources().getColor(
							R.color.calculate_notselected));
			list.get(1).setTextColor(
					mContext.getResources().getColor(
							R.color.calculate_notselecteddeep));
			list.get(3).setTextColor(
					mContext.getResources().getColor(
							R.color.calculate_notselecteddeep));
			list.get(9).setTextColor(
					mContext.getResources().getColor(
							R.color.calculate_notselecteddeep));
			list.get(11).setTextColor(
					mContext.getResources().getColor(
							R.color.calculate_notselecteddeep));
			break;
		case 2:
			list.get(8).setBackgroundColor(
					mContext.getResources().getColor(
							R.color.calculate_text_blue));
			list.get(0).setBackgroundColor(
					mContext.getResources().getColor(
							R.color.calculate_background));
			list.get(4).setBackgroundColor(
					mContext.getResources().getColor(
							R.color.calculate_background));
			list.get(2).setTextColor(
					mContext.getResources().getColor(
							R.color.calculate_notselected));
			list.get(6).setTextColor(
					mContext.getResources().getColor(
							R.color.calculate_notselected));
			for (int i = 1; i < 8; i = i + 2) {
				list.get(i).setTextColor(
						mContext.getResources().getColor(
								R.color.calculate_notselecteddeep));
			}
			break;
		default:
			break;
		}
        logNaviPathData(mAMapNavi);
		// 显示过路费，红绿灯灯数，打车花费
		Log.i(TAG,"[chooseRouteType] end:path="+naviPaths.size());
        
	}
	/**
	 * 计算行车路径的线程
	 */
	class calculateRouteThread extends Thread {
		AMapNaviPath naviPath = null;
		HUDParameterEntity hudParameterEntity = null;

		public calculateRouteThread(AMapNaviPath naviPath, HUDParameterEntity entity) {
			this.naviPath = naviPath;
			this.hudParameterEntity = entity;
		}

		@SuppressWarnings("static-access")
		@Override
		public void run() {
			// BluetoothUpdataObserver.getCommunicationUpdata()
			// .CommunicationUpdata(Bluetooth.initMark);
			// NaviLatLng startLatLng = naviPath.getStartPoint();
			// List<NaviLatLng> CoordList = naviPath.getCoordList();
			// if (CoordList == null) {
			// CoordList = new ArrayList<NaviLatLng>();
			// }
			//
			// int latLngsSize = CoordList.size();
			// if (latLngsSize > 49) {
			// latLngsSize = 49;
			// }
			// 开始导航标志
			// BluetoothUpdataObserver.getCommunicationUpdata()
			// .CommunicationUpdata(Bluetooth.startMark);
			// 暂时不用发送坐标点
			// service.getConsumer().add(
			// new MessageTask(service, HUDParameterEntity
			// .toArrayList(getRoult(CoordList.size(),
			// CoordList.subList(0, latLngsSize),
			// startLatLng, naviPath)),
			// Constants.ZXSendHudDataBeforTypeWithStart));
			startEmulatorNavi();
		}
	}

	private void startEmulatorNavi() {
		Intent emulatorIntent = new Intent(mContext, SimpleNaviActivity.class);
		Bundle bundle = new Bundle();
		bundle.putBoolean(Utils.ISEMULATOR, isNaviRote);
		bundle.putStringArrayList("aMapNaviGuides", (ArrayList<String>) aMapNaviGuides);
		// bundle.putParcelableArrayList("CoordList",
		// (ArrayList<? extends Parcelable>) CoordList);
		bundle.putParcelable("mNaviStart", mStartPoint);
		bundle.putInt(Utils.ACTIVITYINDEX, Utils.SIMPLEROUTENAVI);
		emulatorIntent.putExtras(bundle);
		emulatorIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
		mContext.startActivity(emulatorIntent);

	}

	@Override
	public void onEndEmulatorNavi() {
        isNavigating = false;
	}

	@Override
	public void onGetNavigationText(int arg0, String arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onGpsOpenStatus(boolean arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onInitNaviFailure() {
		// TODO Auto-generated method stub
		Log.e(TAG,"navi init error");
	}

	@Override
	public void onInitNaviSuccess() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onLocationChange(AMapNaviLocation location) {
        if(!App.deviceSettings.onBoardNavi){
            Log.i(TAG,"----- onLocationChange() ------");
            // lxs----------------更新导航速度
            NaviUpdateInfo updateInfo = new NaviUpdateInfo();
            updateInfo.speed = (int)location.getSpeed();
            ProtoMsg protoMsg = new ProtoMsg("updateNaviSpeed", JSON.toJSONString(updateInfo));
            ARHudComm.getInstance().sendToHud(protoMsg.toBytes());
        }
	}
	int remainingDistance = 0;
	@Override
	public void onNaviInfoUpdate(NaviInfo naviInfo) {
        if(!App.deviceSettings.onBoardNavi){
            Log.i(TAG,"----- onNaviInfoUpdate() ------");
            // lxs ----------------更新导航过程信息AR
            ARHudComm.getInstance().sendToAR(AR_Navi.sendNaviInfoToAR(mStartPoint,naviInfo));
            // lxs ----------------发送到HUD
            NaviUpdateInfo naviUpdateInfo = new NaviUpdateInfo();
			naviUpdateInfo.currentRoadName = naviInfo.getCurrentRoadName();
            naviUpdateInfo.nextRoadDistance = naviInfo.getCurStepRetainDistance();
            naviUpdateInfo.nextRoadName = naviInfo.getNextRoadName();
            naviUpdateInfo.nextTurnIcon = naviInfo.getIconType();
            naviUpdateInfo.cameraType = naviInfo.getCameraType();
            naviUpdateInfo.speedLimit = naviInfo.getLimitSpeed();
            naviUpdateInfo.cameraDistance = naviInfo.getCameraDistance();
            ProtoMsg protoMsg = new ProtoMsg("updateNaviInfo", JSON.toJSONString(naviUpdateInfo));
            ARHudComm.getInstance().sendToHud(protoMsg.toBytes());

			remainingDistance = naviInfo.getPathRetainDistance();// 当前导航还剩余的总路程，单位米
        }
	}

	@Override
	@Deprecated
	public void onNaviInfoUpdated(AMapNaviInfo arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onReCalculateRouteForTrafficJam() {
		// TODO Auto-generated method stub

	}
    boolean recalculateForYaw = false;
	@Override
	public void onReCalculateRouteForYaw() {
		// TODO 重新发送整个导航路径信息到AR
        recalculateForYaw = true;
        mAMapNavi.reCalculateRoute(currentStragtegyForNavi);
		Log.w(TAG,"-----偏航------ 重新发送路径信息 ====> AR");
	}

	@Override
	public void onStartNavi(int arg0) {
		// TODO Auto-generated method stub
		isNavigating = true;
        tv_navi_status.setText("停止导航");
	}

	@Override
	public void onTrafficStatusUpdate() {
		// TODO Auto-generated method stub
		// 路况信息变化，更新路况，导航光柱控件显示
		updateCurrentTrafficStatusData();
		// send remainningRoadCondition to hud
	}

	@Override
	public View getInfoContents(Marker arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	void updateCurrentTrafficStatusData(){
		int end = currentNaviPath.getAllLength();
		int start = end - remainingDistance;

		List<AMapTrafficStatus> remainingRoadCondition = mAMapNavi.getTrafficStatuses(start, end);

		TrafficStatusUpdateData trafficStatusUpdateData = new TrafficStatusUpdateData();
		trafficStatusUpdateData.total = end;
		trafficStatusUpdateData.remaining = remainingDistance;
		trafficStatusUpdateData.trafficStatus = remainingRoadCondition;

		ProtoMsg msg = new ProtoMsg("updateTrafficStatus",JSON.toJSONString(trafficStatusUpdateData));
		ARHudComm.getInstance().sendToHud(msg.toBytes());
	}

	@Override
	public View getInfoWindow(Marker marker) {
		return initInfoWindow(marker);
	}

	private View initInfoWindow(final Marker marker) {
		View infoWindow = null;
		switch (inNaviLocionType) {

		case Constants.inNaviLocionType_COLLECTION:
			infoWindow = ((Activity) mContext).getLayoutInflater().inflate(R.layout.pop_car_address_set, null);
			Log.d(TAG, "inNaviLocionType_COLLECTION");
			break;
		case Constants.inNaviLocionType_COMMON:
			Log.d(TAG, "inNaviLocionType_COMMON");
			infoWindow = ((Activity) mContext).getLayoutInflater().inflate(R.layout.pop_car_address_navigation, null);
			Toast.makeText(mContext, mAddressEntity.getNick_address() + " " + mAddressEntity.getReal_address(),
					Toast.LENGTH_LONG).show();

			((TextView) infoWindow.findViewById(R.id.address_name)).setText(mAddressEntity.getNick_address());
			Log.d(TAG, "1");
			((TextView) infoWindow.findViewById(R.id.address)).setText(mAddressEntity.getReal_address());
			if (strAllLength == null) {
				((TextView) infoWindow.findViewById(R.id.pop_address_nav_tv)).setText("到这里");
			} else {
				((TextView) infoWindow.findViewById(R.id.pop_address_nav_tv)).setText(strAllLength + "公里");
			}

			break;

		// ysc20160901 取消点击地图弹出跟随的infoWindow
		case Constants.inNaviLocionType_DIRECT:
			// 点击地图某个点，弹出infoWindow信息框
			Log.d(TAG, "inNaviLocionType_DIRECT");
			// infoWindow = ((Activity)
			// mContext).getLayoutInflater().inflate(R.layout.pop_car_address_navigation_location,
			// null);
			break;

		default:
			break;
		}

		if (isGetInfoWindow) {
			isGetInfoWindow = false;
			// String strPlaceName_name = "";
			if (inNaviLocionType != Constants.inNaviLocionType_COMMON) {
				// strPlaceName_name = serchEditText.getText().toString().trim();
//				((TextView) infoWindow.findViewById(R.id.address_name)).setText(serchEditText.getText().toString().trim());
				Log.d(TAG, "2"); 
//				((TextView) infoWindow.findViewById(R.id.address)).setText(strPlaceName);// ysc此处成功设置了infoWindow的地址信息
				navi_infowindow_rl.setVisibility(View.VISIBLE);
				navi_place_name.setText(strPlaceName);
			}

		}

		/** 到这里，infoWindow button点击事件 
		 * ysc20160927以前的infoWindow显示窗的开始导航按钮显示窗口
		 * */
//		RelativeLayout pop_address_nav_rl = (RelativeLayout) infoWindow.findViewById(R.id.windowinfo_navi);
//
//		pop_address_nav_rl.setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View v) {
//
//				if (inNaviLocionType != Constants.inNaviLocionType_COLLECTION) {
//					showPOP(marker);
//				} else {
//					Intent emulatorIntent = new Intent(mContext, ComAddressSetavt.class);
//					Bundle bundle = new Bundle();
//					bundle.putString("areaid", serchEditText.getText().toString());// 地区
//					Log.d(TAG, "3");
//					bundle.putString("address", strPlaceName);// 实际地址
//					bundle.putString("longitude", mEndPoint.getLongitude() + "");
//					bundle.putString("latitude", mEndPoint.getLatitude() + "");
//					emulatorIntent.putExtras(bundle);
//					((Activity) mContext).startActivity(emulatorIntent);
//					((Activity) mContext).finish();
//				}
//
//			}
//
//		});
		
		return infoWindow;

	}

	/**
	 * 现实POP(模拟导航、开始导航、结束导航)
	 * 
	 * @param marker
	 * @return
	 */
	private boolean showPOP(Marker marker) {
		switch (mMapClickMode) {
		case MAP_CLICK_END:
			if (navigationPopupWindow == null) {
				navigationPopupWindow = new PopupWindow(mContext);
				Log.d(TAG, "弹出开始导航、结束导航按钮");
				
				pop_view = View.inflate(mContext, R.layout.popupwindow_navigation, null);
				navigationPopupWindow.setContentView(pop_view);
				navigationPopupWindow.setWidth(LayoutParams.MATCH_PARENT);
				navigationPopupWindow.setHeight(LayoutParams.WRAP_CONTENT);
				navigationPopupWindow.setFocusable(true);
				navigationPopupWindow.setOutsideTouchable(false);
				navigationPopupWindow.setAnimationStyle(R.style.popup_fade_anim);
				// 20%黑
				ColorDrawable dw = new ColorDrawable(0x33000000);
				navigationPopupWindow.setBackgroundDrawable(dw);
				
				pop_view.setOnTouchListener(new OnTouchListener() {
					public boolean onTouch(View v, MotionEvent event) {
						int height = pop_view.findViewById(R.id.pop_layout).getTop();
						int y = (int) event.getY();
						if (event.getAction() == MotionEvent.ACTION_UP) {
							if (y < height) {
								navigationPopupWindow.dismiss();
							}
						}
						return true;
					}
				});
				/** 开始导航 */
				pop_view.findViewById(R.id.pop_begin).setOnClickListener(this);
				/** 手机导航 */
				pop_view.findViewById(R.id.pop_startNavi_byPhone).setOnClickListener(this);
				/** 模拟导航 */
				pop_view.findViewById(R.id.pop_simulate).setOnClickListener(this);
				/** 结束导航 */
				pop_view.findViewById(R.id.stop).setOnClickListener(this);
				// 当系统环境是调试环境的时候，设置模拟导航显示和隐藏
				if (SystemInfo.isDebug) {
					pop_view.findViewById(R.id.simulate_layout).setVisibility(View.GONE);
				}
			}

			int[] location = new int[2];
			tabView.findViewById(R.id.com_search_map_et).getLocationOnScreen(location);

			navigationPopupWindow.showAtLocation(tabView.findViewById(R.id.com_search_map_et), Gravity.NO_GRAVITY,
					location[0], location[1] - navigationPopupWindow.getHeight());

			break;

		default:
			break;
		}

		return false;

	}

	/**
	 * 现实POP(模拟导航、开始导航、结束导航)
	 * 
	 * @param
	 * @return
	 */
	private boolean showPOP2() {
		switch (mMapClickMode) {
		case MAP_CLICK_END:
			mutipleCalculate();// 开始多路径规划
			break;
		default:
			break;
		}
		return false;
	}


	public void multCaculateForDs3(ComEntity from,ComEntity pass,ComEntity to){
		Log.i(TAG,"[multCaculateForDs3] begin");
		if(null == to  || !to.isValid()){
			Log.e(TAG,"错误的目标位置");
			return;
		}
        // 起点和终点
		if(null == from || !from.isValid()){
			from = currPos;
		}
		Log.i(TAG,"[multCaculateForDs3]begin:endpoint="+to.toString()+";start="+from.toString());
		mStartPointList.clear();
		mEndPointList.clear();
		mWayPointsList.clear();
		try {
			NaviLatLng start = new NaviLatLng(Double.parseDouble(from.getPlace_lat()),Double.parseDouble(from.getPlace_lng()));
			NaviLatLng end = new NaviLatLng(Double.parseDouble(to.getPlace_lat()),Double.parseDouble(to.getPlace_lng()));
			mStartPointList.add(start);
			mEndPointList.add(end);
		}catch(NumberFormatException ex){
			Log.e(TAG,"ds3:invalid start or end point"+from.getPlace_lat()+":"+from.getPlace_lng());
			return;
		}
        // 途经点
		if(null != pass && pass.isValid()){
			try {
				NaviLatLng pp = new NaviLatLng(Double.parseDouble(pass.getPlace_lat()),Double.parseDouble(pass.getPlace_lng()));
				mWayPointsList.add(pp);
			}catch(NumberFormatException ex){
				Log.e(TAG,"ds3:invalid pass point"+pass.getPlace_lat()+":"+pass.getPlace_lng());
			}
		}


		mulCalculateDriveRoute(mStartPointList, mEndPointList, mWayPointsList);
	}


	private static class NaviPrefer{
		private boolean congestion;
		private boolean avoidhightspeed;
		private boolean cost;
		private boolean hightspeed;

		public boolean isCongestion() {
			return congestion;
		}

//		public void setCongestion(boolean congestion) {
//			this.congestion = congestion;
//		}


		public boolean isAvoidhightspeed() {
			return avoidhightspeed;
		}

//		public void setAvoidhightspeed(boolean avoidhightspeed) {
//			this.avoidhightspeed = avoidhightspeed;
//		}

		public boolean isCost() {
			return cost;
		}

//		public void setCost(boolean cost) {
//			this.cost = cost;
//		}

		public boolean isHightspeed() {
			return hightspeed;
		}

//		public void setHightspeed(boolean hightspeed) {
//			this.hightspeed = hightspeed;
//		}

		public void calcPrefer(int mode) {

			switch (mode){
				case 0:
					congestion = true;
					avoidhightspeed = true;
					cost = false;
					hightspeed = true;
					break;
				case 1:
					congestion = true;
					avoidhightspeed = true;
					cost = true;
					hightspeed = false;
					break;
				case 2:
					congestion = true;
					avoidhightspeed = true;
					cost = true;
					hightspeed = false;

					break;
				case 3:
					congestion = true;
					avoidhightspeed = false;
					cost = false;
					hightspeed = true;
					break;
				default:
					congestion = true;
					avoidhightspeed = false;
					cost = false;
					hightspeed = true;
					break;
			}
		}
	}

	private void mulCalculateDriveRoute(List<NaviLatLng> startPointList,List<NaviLatLng> endPointListPointList,List<NaviLatLng> wayPointsList){
		if(null == mAMapNavi){
			Log.e(TAG,"mAMapNavi is null");
			return;
		}

		if(null == endPointListPointList || endPointListPointList.size() < 1){
			Log.e(TAG,"endPointListPointList is empty");
			return;
		}

		if(null == startPointList || startPointList.size() < 1){
			Log.e(TAG,"startPointList is empty");
			return;
		}
		Log.i(TAG,"[mutipleCalculate]begin:endpoint="+mEndPointList.toString()+";start="+mStartPoint.toString());


		if(isNavigating){
			mAMapNavi.stopNavi();
			isNavigating = false;
			endCalculate();
		}

		NaviPrefer prefer = new NaviPrefer();
		int mode = -1;
		try {
			String val = SharedPreTools.getString(mContext, "cof_navipathtype", "-1");
			mode = Integer.parseInt(val);
			prefer.calcPrefer(mode);
		}catch(NumberFormatException ex){
			Log.e(TAG,"error input :mode="+ex.toString());
			mode = -1;
		}


		Log.i(TAG,"路线策略：congestion＝"+prefer.isCongestion()+";avoidhightspeed="+ prefer.isAvoidhightspeed() +";cost="+ prefer.isCost() +";hightspeed="+ prefer.isHightspeed());


		int strategy = 0;
		try {
			mAMapNavi.setReCalculateRouteForYaw(true);// 偏航的时候重新计算路径
            mAMapNavi.setReCalculateRouteForTrafficJam(true); // 拥堵的时候重新计算路径
			// 再次强调，最后一个参数为true时代表多路径，否则代表单路径
			strategy = mAMapNavi.strategyConvert(prefer.isCongestion(), prefer.isAvoidhightspeed(), prefer.isCost(), prefer.isHightspeed(), true);
            currentStragtegyForNavi = strategy;
        } catch (Exception e) {
			strategy = PathPlanningStrategy.DRIVING_MULTIPLE_ROUTES_DEFAULT_AVOID_CONGESTION_SHORTEST_DISTANCE;
			e.printStackTrace();
		}
		mAMapNavi.calculateDriveRoute(startPointList, endPointListPointList, wayPointsList, strategy);// lxs

	}
    int currentStragtegyForNavi = 0;


	private void mutipleCalculate(){
		Log.i(TAG,"[mutipleCalculate] begin");
		mStartPointList.clear();
		mStartPointList.add(mStartPoint);
		if(AddWayPointsActivity.wayPointArrayList.size()>0){
			for(int i = 0;i<AddWayPointsActivity.wayPointArrayList.size();i++){
				NaviLatLng latLng = new NaviLatLng();
				String latitude = AddWayPointsActivity.wayPointArrayList.get(i).getloca_lat();
				String longitude = AddWayPointsActivity.wayPointArrayList.get(i).getloca_lng();
				latLng.setLatitude(Float.parseFloat(latitude));
				latLng.setLongitude(Float.parseFloat(longitude));
				mWayPointsList.add(latLng);
			}
		}
		mulCalculateDriveRoute(mStartPointList, mEndPointList, mWayPointsList);
	}
	
	//弹出popUpWindow选择使用手机导航还是HUD导航
	private void showChooseNavi() {
		if (navigationPopupWindow == null) {
			navigationPopupWindow = new PopupWindow(mContext);
			pop_view = View.inflate(mContext, R.layout.popupwindow_navigation, null);
			navigationPopupWindow.setContentView(pop_view);
			navigationPopupWindow.setWidth(LayoutParams.MATCH_PARENT);
			navigationPopupWindow.setHeight(LayoutParams.WRAP_CONTENT);
			navigationPopupWindow.setFocusable(true);
			navigationPopupWindow.setOutsideTouchable(false);
			navigationPopupWindow.setAnimationStyle(R.style.popup_fade_anim);
			// 20%黑
			ColorDrawable dw = new ColorDrawable(0x33000000);
			navigationPopupWindow.setBackgroundDrawable(dw);

			pop_view.setOnTouchListener(new OnTouchListener() {
				public boolean onTouch(View v, MotionEvent event) {
					int height = pop_view.findViewById(R.id.pop_layout)
							.getTop();
					int y = (int) event.getY();
					if (event.getAction() == MotionEvent.ACTION_UP) {
						if (y < height) {
							navigationPopupWindow.dismiss();
						}
					}
					return true;
				}
			});
			/** 开始导航 */
			pop_view.findViewById(R.id.pop_begin).setOnClickListener(this);
			/** 手机导航 */
			pop_view.findViewById(R.id.pop_startNavi_byPhone)
					.setOnClickListener(this);
			/** 模拟导航 */
			pop_view.findViewById(R.id.pop_simulate).setOnClickListener(this);
			/** 结束导航 */
			pop_view.findViewById(R.id.stop).setOnClickListener(this);
			pop_view.findViewById(R.id.pop_layout).setOnClickListener(this);
			if (SystemInfo.isDebug) {
				pop_view.findViewById(R.id.simulate_layout).setVisibility(
						View.GONE);
			}
		}
		int[] location = new int[2];
		tabView.findViewById(R.id.com_search_map_et).getLocationOnScreen(
				location);
		navigationPopupWindow.showAtLocation(
				tabView.findViewById(R.id.com_search_map_et),
				Gravity.NO_GRAVITY, location[0], location[1]
						- navigationPopupWindow.getHeight());
	}
	
	@Override
	public void onInfoWindowClick(Marker arg0) {
		// TODO Auto-generated method stub

	}

	/**
	 * 开始进行poi搜索
	 */
	protected void doSearchQuery(String reslut) {
		Log.d(TAG, "poi搜索_doSearchQuery");
		int currentPage = 0;
		query = new PoiSearch.Query(reslut, "", SystemInfo.City);// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
		query.setPageSize(10);// 设置每页最多返回多少条poiitem
		query.setPageNum(currentPage);// 设置查第一页
		poiSearch = new PoiSearch(mContext, query);
		poiSearch.setOnPoiSearchListener(this);
		poiSearch.searchPOIAsyn();
	}

	@Override
	public boolean onMarkerClick(Marker arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterTextChanged(Editable s) {
		// TODO Auto-generated method stub

	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onGeocodeSearched(GeocodeResult arg0, int arg1) {
		// TODO Auto-generated method stub

	}

	/**
	 * 逆地理编码回调
	 */
	@Override
	public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
		Log.i(TAG,"onRegeocodeSearched() ====>");
		if (rCode == 0) {
			if (result != null && result.getRegeocodeAddress() != null
					&& result.getRegeocodeAddress().getFormatAddress() != null) {
				// 点击地图，逆地理编码回调，设置地址
				strPlaceName = result.getRegeocodeAddress().getFormatAddress();
				strPlaceAddress = result.getRegeocodeAddress().getTownship();
				
				LatLng start = new LatLng(mStartPoint.getLatitude(),mStartPoint.getLongitude());
				LatLng end = new LatLng(mEndPoint.getLatitude(), mEndPoint.getLongitude());
				
				float distance = (float)AMapUtils.calculateLineDistance(start, end) / 1000;
				distance = (float)Math.round(distance*100)/100;
				strPlaceDistance = distance + "km";

				Log.d(TAG, "strDistance = " + strPlaceDistance);
				Log.d(TAG, "getNeighborhood()="+result.getRegeocodeAddress().getNeighborhood());
				Log.d(TAG, "strPlaceName1=" + strPlaceName);
				
				// showToast(strPlaceName);
				// 搜索成功后清空输入框
				serchEditText.setText("");
				isGetInfoWindow = true;
				mEndMarker.showInfoWindow();
				Log.d(TAG, "onRegeocodeSearched_"+"strPlaceName="+strPlaceName);
				// ysc20160901  地图点击POI信息
				navi_infowindow_rl.setVisibility(View.VISIBLE);
				navi_place_name.setText(strPlaceName);
				navi_place_address.setText(strPlaceAddress);
				navi_place_distance.setText(strPlaceDistance);
				
				favoritesEntity.setPlace_lng(mEndPoint.getLongitude()+"");
				Log.d(TAG, "onRegeocodeSearched_经度"+mEndPoint.getLongitude()+"");
				favoritesEntity.setPlace_lat(mEndPoint.getLatitude()+"");
				Log.d(TAG, "onRegeocodeSearched_纬度"+mEndPoint.getLatitude()+"");
				
				collect_iv.setImageResource(R.drawable.icon_collect_info);
				isCollectedChecked = false;
				Log.d(TAG, "移动一下坐标点"+isCollectedChecked);
				
			} else {
				strPlaceName = "";
				// mContext.showToast("没有搜索到地址");
			}
		} else {
			strPlaceName = "";
			// showToast("网络异常");
		}

	}

	@Override
	public void onMapClick(LatLng latLng) {

		strPlaceName = "";
		// 默认不接受任何操作
		if (mMapClickMode == MAP_CLICK_NO || Constants.inNaviLocionType_COMMON == inNaviLocionType) {
			return;
		}

		// 其他情况根据起点、途经点、终点不同逻辑处理不同
		addPointToMap(latLng);
		regeocodeQuery(new LatLonPoint(latLng.latitude, latLng.longitude));
		Log.i(TAG, "latitude:" + latLng.latitude + " longitude:" + latLng.longitude);

	}

	/**
	 * 根据坐标点搜索地名 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
	 */
	private void regeocodeQuery(LatLonPoint latLonPoint) {
		// 清空输入框的内容
		serchEditText.setText("");
		RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 500, GeocodeSearch.AMAP);
		geocoderSearch.getFromLocationAsyn(query);
	}

	/**
	 * 画出坐标点
	 * 
	 * @param latLng
	 */
	private void addPointToMap(LatLng latLng) {

		NaviLatLng naviLatLng = new NaviLatLng(latLng.latitude, latLng.longitude);
		switch (mMapClickMode) {
		// 点击地图选择了终点,画出终点坐标，并且显示终点，隐藏算路视图
		case MAP_CLICK_END:
			animateCameraToCenter(latLng);
			mEndMarker.setPosition(latLng);
			mEndPointList.clear();
			mEndPoint = naviLatLng;
			mEndPointList.add(mEndPoint);
			endCalculate();
			break;
		}

	}

	public void endCalculate(){
		//选择其他的目的地就结束算路（隐藏视图，清除途经点）
		navi_infowindow_rl.setVisibility(View.VISIBLE);
		mainLinear.setVisibility(View.VISIBLE);
		re.setVisibility(View.GONE);
		re.findViewById(R.id.distance_shortest).setEnabled(true);	
		re.findViewById(R.id.methord_three).setEnabled(true);	
		//路径刚刚规划成功还是默认选择第一条
		seletedRoutePath = 0;
		isRouting = false;
		mWayPointsList.clear();
		AddWayPointsActivity.wayPointArrayList.clear();
	}
	/**
	 * 将固定坐标点移动到中心位置
	 * 
	 * @param latLng
	 */
	private void animateCameraToCenter(LatLng latLng) {
		float f = 15;
		int w = StringUtil.getScreenWidthPixels(mContext);
		if (w == 1280) {
			f = 14;
		} else if (w < 1280) {
			f = 13;
		}
		aMap.animateCamera(new com.amap.api.maps.CameraUpdateFactory().newLatLngZoom(latLng, f));
	}
	private ComEntity currPos = new ComEntity();
	// 定位当前位置
	@Override
	public void onLocationChanged(AMapLocation amapLocation) {
		if (mListener != null && amapLocation != null && amapLocation.getErrorCode() == 0) {
			// 显示系统小蓝点
			if (!isCenter) {
				mListener.onLocationChanged(amapLocation);
				isCenter = true;
			}
			Log.d(TAG,"定位成功，当前位置："+amapLocation.getPoiName());

			currPos.setPlace_name("我的位置");
			currPos.setPlace_address(amapLocation.getAddress());
			currPos.setPlace_lng(String.valueOf(amapLocation.getLongitude()));
			currPos.setPlace_lat(String.valueOf(amapLocation.getLatitude()));

			mStartPoint.setLatitude(amapLocation.getLatitude());
			mStartPoint.setLongitude(amapLocation.getLongitude());
//			mStartPointList.add(mStartPoint);
			SystemInfo.City = amapLocation.getCity();
			my_location.setText(amapLocation.getPoiName());
			initMapAndNavi();
			// 查询实时天气情况
			searchliveweather();
			SharedPreTools.putString(mContext, Common.LAT, amapLocation.getLatitude() + "");
			SharedPreTools.putString(mContext, Common.LNG, amapLocation.getLongitude() + "");
			SharedPreTools.putString(mContext, Common.LOACTION, amapLocation.getProvince() + amapLocation.getCity()
					+ amapLocation.getDistrict());
		} else {
			Log.i(TAG, "定位失败" + "Error Code" + amapLocation.getErrorCode() + amapLocation.getErrorInfo());
		}

	}

	/**
	 * 获取单双号限行
	 * 
	 * @param url
	 */
	private void getTrafficControls(String url) {
		HashMap<String, String> map = new HashMap<String, String>();
		int inDex = SystemInfo.City.indexOf("市");
		if (inDex > -1) {
			map.put("cityname", SystemInfo.City.substring(0, inDex));
		} else {
			map.put("cityname", SystemInfo.City);
		}
		HttpUtil.getInstance(mContext).Post(App.ZZD_REQUEST_RESTRICT, map, new HttpResponseListener() {

			@Override
			public void onSuccess(RespEntity respEntity) {

				System.out.println(respEntity.getMsg());
			}

			@Override
			public void onLoading(int vurrent) {

			}

			@Override
			public void onFailure(String result) {

			}
		});

	}

	/**
	 * 初始化地图和导航相关内容
	 */
	private void initMapAndNavi() {
		// 初始化Marker添加到地图
		// mStartMarker = aMap.addMarker(new MarkerOptions()
		// .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
		// .decodeResource(mContext.getResources(),
		// R.drawable.start))));
		MarkerOptions endMarkerOptions = new MarkerOptions()
				.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(mContext.getResources(),
						R.drawable.end)));
		endMarkerOptions.draggable(true);

		if (mEndMarker == null) {
			mEndMarker = aMap.addMarker(endMarkerOptions);
		}

		mRouteOverLay = new RouteOverLay(aMap, null,mContext);
		((TextView) tabView.findViewById(R.id.navi_title_city)).setText(SystemInfo.City);

		// if (inNaviLocionType == Constants.inNaviLocionType_COMMON) {
		// mAddressEntity = (ComAddressEntity) mContextgetIntent().getExtras()
		// .getSerializable("ComAddressEntity");
		// mEndPoint.setLatitude(Double.parseDouble(mAddressEntity
		// .getLatitude()));
		// mEndPoint.setLongitude(Double.parseDouble(mAddressEntity
		// .getLongitude()));
		// // 其他情况根据起点、途经点、终点不同逻辑处理不同
		// addPointToMap(new LatLng(mEndPoint.getLatitude(),
		// mEndPoint.getLongitude()));
		// isGetInfoWindow = true;
		// mEndMarker.showInfoWindow();
		// }
	}
	
	/**
	 * 激活定位
	 */
	@Override
	public void activate(OnLocationChangedListener listener) {
		mListener = listener;
		if (mlocationClient == null) {
			
			/**AMapLocationClient定位客户端*/
			// 初始化定位参数
			mlocationClient = new AMapLocationClient(mContext);
			// 设置定位监听
			mlocationClient.setLocationListener(this);

			/**AMapLocationClientOption定位参数*/
			// 初始化AMapLocationClientOption对象
			mLocationOption = new AMapLocationClientOption();
			// 设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
			mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);
			// 可选，设置是否单次定位。默认是false
			mLocationOption.setOnceLocation(true);
			//获取最近3s内精度最高的一次定位结果：
			//设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
//			mLocationOption.setOnceLocationLatest(true);
			//设置定位间隔,单位毫秒,默认为2000ms，最低1000ms
			mLocationOption.setInterval(2000);
			// 可选，设置定位同时是否返回逆地理地址信息。默认是ture
			mLocationOption.setNeedAddress(true);
			// 设置是否强制刷新WIFI，默认为强制刷新
			mLocationOption.setWifiActiveScan(true); 
			// 设置是否允许模拟位置,默认为false，不允许模拟位置
			mLocationOption.setMockEnable(false);
			
			/**启动定位*/
			// 给定位客户端对象设置定位参数
			mlocationClient.setLocationOption(mLocationOption);
			//启动定位
			mlocationClient.startLocation();
			
			// 备注：
			// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
			// 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
			// 在定位结束后，在合适的生命周期调用onDestroy()方法
			// 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
		}
		
		// 备注：
		// mListener = listener;
		// if (mAMapLocationManager == null) {
		// mAMapLocationManager = LocationManagerProxy.getInstance(mContext);
		// // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
		// // 注意设置合适的定位时间的间隔，并且在合适时间调用removeUpdates()方法来取消定位请求
		// // 在定位结束后，在合适的生命周期调用destroy()方法
		// // 其中如果间隔时间为-1，则定位只定一次
		// mAMapLocationManager.requestLocationData(
		// LocationProviderProxy.AMapNetwork, -1, 10, this);
		// }
	}

	/**
	 * 停止定位
	 */
	@Override
	public void deactivate() {
		mListener = null;
		if (mlocationClient != null) {
			mlocationClient.stopLocation();
			mlocationClient.onDestroy();
		}
		mlocationClient = null;
	}

	// 计算驾车路线
	private void calculateDriveRoute(String naviType) {
		if (!isCalculateSuccess) {
			// showProgressDialog("提示", "路径计算中请稍后...");
			NaviParams params = new NaviParams();
			// JSONObject jsonObject = new JSONObject();
			try {
				// longitude 经度
				// latitude 纬度
				// naviPlanRouterTypeFlag
				// naviType
				params.latitude = mEndPointList.get(0).getLatitude();
				// jsonObject.put("latitude",
				// mEndPointList.get(0).getLatitude());
				params.longitude = mEndPointList.get(0).getLongitude();
				// jsonObject.put("longitude",
				// mEndPointList.get(0).getLongitude());
				Log.i(TAG, "目的地" + mEndPointList.get(0).getLatitude() + "*"
						+ mEndPointList.get(0).getLongitude());
				params.naviPlanRouterTypeFlag = InstructionSet.INSTRUCTION_AUTH_HOTSPOT_TO_HUD;
				// jsonObject.put("naviPlanRouterTypeFlag",
				// InstructionSet.INSTRUCTION_AUTH_HOTSPOT_TO_HUD);//
				// 规划方案（具体参数参照高德官方API）
				// jsonObject.put("naviType", naviType);// 导航类型 1模拟 2真实导航
				params.naviType = naviType;
				params.waypoints = mWayPointsList;
				params.naviPathSeletedIndex = seletedRoutePath;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Log.i(TAG,"json String:"+params.toJsonString());
			MessageManager.send(Integer.parseInt(SystemInfo.getSendPORT()),
					new RequestEntity(params.toJsonString(),
							InstructionSet.INSTRUCTION_AUTH_NAVI_STATRT_TO_HUD
									+ ""));
			// isCalculateSuccess = mAMapNavi.calculateDriveRoute(mStartPoints,
			// mEndPoints, null, AMapNavi.DrivingFastestTime);
			// if (!isCalculateSuccess) {
			// Log.i(TAG, "路线计算失败,检查参数情况");
			// }
		} else {

		}

	}

	/**
	 * 在搜索界面搜索”世界之窗“，点第一个结果”世界之窗“，然后在地图上添加终点，并显示infowindow
	 * 
	 */
	public void addPointToMap(NaviHistoryEntity naviHistoryEntity) {
		// 搜索完毕后根据坐标点画出
		addPointToMap(new LatLng(Double.parseDouble(naviHistoryEntity.getloca_lat()), Double.parseDouble(naviHistoryEntity.getloca_lng())));
		strPlaceName = naviHistoryEntity.getloca_nickname();
		strPlaceAddress = naviHistoryEntity.getloca_address();
		Log.d(TAG, "addPointToMap_"+"strPlaceName2=" + strPlaceName);
		if(strPlaceName != null && strPlaceName.length()>0)
			serchEditText.setText(strPlaceName);
		isGetInfoWindow = true;
		mEndMarker.showInfoWindow();

		Log.d(TAG, "mEndMarker+addPointToMap");

	}


	
	/** 根据收藏夹经纬度画出指针位置 */
	public void addPointToMap2(FavoritesEntity favoritesEntity) {
		Log.d(TAG, "addPointToMap2---------收藏夹中地址点击，显示到地图，根据经度和纬度画出点坐标icon插在地图上");
		// 搜索完毕后根据坐标点画出
		addPointToMap(new LatLng(Double.parseDouble(favoritesEntity.getPlace_lat()), Double.parseDouble(favoritesEntity.getPlace_lng())));
		strPlaceName = favoritesEntity.getPlace_name();
		strPlaceAddress = favoritesEntity.getPlace_address();
		Log.d(TAG, "addPointToMap2_"+"strPlaceName2=" + strPlaceName);
		if(strPlaceName != null && strPlaceName.length()>0)
			serchEditText.setText(strPlaceName);
		LatLng start = new LatLng(mStartPoint.getLatitude(),mStartPoint.getLongitude());
		
		Float end_lat = Float.parseFloat(favoritesEntity.getPlace_lat());
		Float end_lng = Float.parseFloat(favoritesEntity.getPlace_lng());
		LatLng end = new LatLng(end_lat, end_lng);
		float distance = (float)AMapUtils.calculateLineDistance(start, end) / 1000;
		distance = (float)Math.round(distance*100)/100;
		strPlaceDistance = distance + "km";
//		strPlaceDistance = favoritesEntity.getPlace_lng();
		isGetInfoWindow = true;
		mEndMarker.showInfoWindow();
	}


	/** 根据收藏夹经纬度画出指针位置 */
	public void addPointToMap2(ComEntity comEntity) {
		Log.d(TAG, "addPointToMap2---------收藏夹中地址点击，显示到地图，根据经度和纬度画出点坐标icon插在地图上");
		// 搜索完毕后根据坐标点画出
		addPointToMap(new LatLng(Double.parseDouble(comEntity.getPlace_lat()), Double.parseDouble(comEntity.getPlace_lng())));
		strPlaceName = comEntity.getPlace_name();
		strPlaceAddress = comEntity.getPlace_address();
		Log.d(TAG, "addPointToMap2_"+"strPlaceName2=" + strPlaceName);
		if(strPlaceName != null && strPlaceName.length()>0)
			serchEditText.setText(strPlaceName);
		LatLng start = new LatLng(mStartPoint.getLatitude(),mStartPoint.getLongitude());

		double end_lat = Double.parseDouble(comEntity.getPlace_lat());
		double end_lng = Double.parseDouble(comEntity.getPlace_lng());
		LatLng end = new LatLng(end_lat, end_lng);
		float distance = AMapUtils.calculateLineDistance(start, end) / 1000;
		distance = (float)Math.round(distance*100)/100;
		strPlaceDistance = distance + "km";
//		strPlaceDistance = favoritesEntity.getPlace_lng();
		isGetInfoWindow = true;
		mEndMarker.showInfoWindow();
	}
	
	/** 根据收藏夹经纬度画出指针位置 */
	public void addPointToMap3(ComEntity comEntity) {
		Log.d(TAG, "addPointToMap3---------点击家或者公司地址，显示到地图，根据经度和纬度画出点坐标icon插在地图上");
		// 搜索完毕后根据坐标点画出
		addPointToMap(new LatLng(Double.parseDouble(comEntity.getPlace_lat()), Double.parseDouble(comEntity.getPlace_lng())));
		strPlaceName = comEntity.getPlace_name();
		strPlaceAddress = comEntity.getPlace_address();
		Log.d(TAG, "addPointToMap3_"+"strPlaceName2=" + strPlaceName);
		if(strPlaceName != null && strPlaceName.length()>0)
			serchEditText.setText(strPlaceName);
		isGetInfoWindow = true;
		mEndMarker.showInfoWindow();
	}

	/**
	 * 听写UI监听器
	 */
	private RecognizerDialogListener recognizerDialogListener = new RecognizerDialogListener() {
		public void onResult(RecognizerResult results, boolean isLast) {
			if(!isLast)
				printResult(results);
		}

		/**
		 * 识别回调错误.
		 */
		public void onError(SpeechError error) {
			System.out.println(error.getPlainDescription(true));
		}

	};

	private void printResult(RecognizerResult results) {
		// 用HashMap存储听写结果
		HashMap<String, String> mIatResults = new LinkedHashMap<String, String>();
		String[] redundantCharacter = { "到", "往", "去" };

		String text = JsonParser.parseIatResult(results.getResultString());
		JSONObject resultJson = null;
		String sn = null;
		// 读取json结果中的sn字段
		try {
			resultJson = new JSONObject(results.getResultString());
			sn = resultJson.optString("sn");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		mIatResults.put(sn, text);
		final StringBuffer resultBuffer = new StringBuffer();
		for (String key : mIatResults.keySet()) {
			resultBuffer.append(mIatResults.get(key));
		}
		String result = resultBuffer.toString();

		for (int i = 0; i < redundantCharacter.length; i++) {
			int index = resultBuffer.indexOf(redundantCharacter[i]);
			if (index > -1) {
				result = resultBuffer.substring(index + 1);
			}
		}
		if (result.length() != 0 ) {//&& ((Boolean) resultJson.opt("ls"))
			Log.d(TAG, "语音识别：" + result.toString());

			Intent intent = new Intent(mContext, NaviSerchActivity.class);
			Bundle bundle = new Bundle();
			bundle.putString("voiceresult",result);
			intent.putExtras(bundle);

			((Activity) mContext).startActivityForResult(intent, RequestCode.REQUESTCODE_NAVI);
		}

	}

	public void onDestroy() {
		mapView.onDestroy();
		// 删除监听
		mAMapNavi.removeAMapNaviListener(this);
		// 这是最后退出页，所以销毁导航和播报资源
		mAMapNavi.destroy();// 销毁导航
		if (TTSController.getInstance(mContext) != null) {
			TTSController.getInstance(mContext).stopSpeaking();
			TTSController.getInstance(mContext).destroy();
		}
		if (iatController != null) {
			iatController.onDestory();
		}
	}

	public void onResume() {
		mapView.onResume();
		//如果正在算路，可能添加了途经点，每次再回来重新算路
		if(isRouting){
//			mutipleCalculate();
		}

		checkSpeaker();
	}

	private void searchliveweather() {
		mquery = new WeatherSearchQuery("北京市", WeatherSearchQuery.WEATHER_TYPE_LIVE);// 检索参数为城市和天气类型，实时天气为1、天气预报为2
		mweathersearch = new WeatherSearch(mContext);
		mweathersearch.setOnWeatherSearchListener(this);
		mweathersearch.setQuery(mquery);
		mweathersearch.searchWeatherAsyn(); // 异步搜索
	}

	/**
	 * 天气预报接口回调
	 */
	@Override
	public void onWeatherForecastSearched(LocalWeatherForecastResult arg0, int rCode) {
		if (rCode == 0) {
		} else {
			Log.e(TAG, "获取天气失败");
		}
	}

	/**
	 * 实时天气回调接口
	 */
	@Override
	public void onWeatherLiveSearched(LocalWeatherLiveResult liveResult, int rCode) {
		if (rCode == 0) {
			LocalWeatherLive live = liveResult.getLiveResult();
			// 获取当前天气
			weatherTextView.setText(live.getWeather());
			// 获取当前温度
			temperatureTextView.setText(live.getTemperature() + "℃");

			SystemInfo.Weather = live.getWeather();
			SystemInfo.Temperature = live.getTemperature()+"℃";

		} else {
			Log.e(TAG, "获取天气失败");
		}
	}

	@Override
	public void OnUpdateTrafficFacility(TrafficFacilityInfo arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void hideCross() {
		// TODO Auto-generated method stub

	}

	@Override
	public void hideLaneInfo() {
		// TODO Auto-generated method stub

	}

	@Override
	public void showCross(AMapNaviCross arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void showLaneInfo(AMapLaneInfo[] arg0, byte[] arg1, byte[] arg2) {
		// TODO Auto-generated method stub

	}

	/** 弹窗-是否连接HUD */
//	private void showKeylessDialog() {
//
//		final Dialog exitDialog = new Dialog(mContext, R.style.my_dialog);
//		Log.d(TAG, "弹出连接hud提示");
//		View v = LayoutInflater.from(mContext).inflate(R.layout.dialog_keyless, null);
//
//		if (UdpTools.isContent) {
//			((TextView) v.findViewById(R.id.dialog_text)).setText("HUD正在进行导航...");
//		} else {
//			((TextView) v.findViewById(R.id.dialog_text)).setText("没有发现HUD...");
//		}
//
//		v.findViewById(R.id.dialog_cancel).setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View arg0) {
//				// 取消hud导航
//				exitDialog.dismiss();
//				MessageManager.send(Integer.parseInt(SystemInfo.getSendPORT()), new RequestEntity("",
//						InstructionSet.INSTRUCTION_AUTH_NAVI_STOP_HUD_TO_HUD + ""));
//			}
//		});
//		v.findViewById(R.id.dialog_continue).setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View arg0) {
//				// 继续导航把当前提示框隐藏
//				exitDialog.dismiss();
//			}
//		});
//		LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
//		exitDialog.addContentView(v, params);
//		exitDialog.show();
//	}

	@Override
	@Deprecated
	public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo[] arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void notifyParallelRoad(int arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onArriveDestination(NaviStaticInfo arg0) {
		// TODO Auto-generated method stub
        isNavigating = false; // 实际导航结束，已经抵达目的地
        tv_navi_status.setText("开始导航");
	}

	private  HashMap<Integer, AMapNaviPath> naviPaths ;
	int[] pathIds;
	@Override
	public void onCalculateMultipleRoutesSuccess(int[] routeIds) {
		Log.i(TAG,"onCalculateMultipleRoutesSuccess");
		//多路径计算成功回调
		navi_go.setVisibility(View.GONE);
		pathIds = routeIds;
		if(null != naviPaths)
			naviPaths.clear();
		naviPaths = mAMapNavi.getNaviPaths();
//		naviPaths = (HashMap<Integer, AMapNaiPath>)mAMapNavi.getNaviPaths().clone();

		Log.i(TAG,"[CalculateMultipleRoutesSuccess]ids="+pathIds.length);
		Log.i(TAG,"[CalculateMultipleRoutesSuccess]paths="+naviPaths.size());

		//显示路线规划完成视图
		if(naviPaths.size()<1){
			Toast.makeText(mContext, "规划路径0条", Toast.LENGTH_SHORT).show();
			return;
		}
		isRouting = true;
		navi_infowindow_rl.setVisibility(View.GONE);
		mainLinear.setVisibility(View.GONE);
		re.setVisibility(View.VISIBLE);
		re.findViewById(R.id.distance_shortest).setEnabled(true);	
		re.findViewById(R.id.methord_three).setEnabled(true);	
		//路径刚刚规划成功还是默认选择第一条
		seletedRoutePath = 0;
		chooseRouteType();
		displayUiHandler.sendEmptyMessage(0);
	}



	@Override
	public void updateAimlessModeCongestionInfo(AimLessModeCongestionInfo arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void updateAimlessModeStatistics(AimLessModeStat arg0) {
		// TODO Auto-generated method stub
		
	}
	
	private void showStrategy(){
		//计算路径成功后显示所有数据：红绿灯灯数、过路费、计算策略、耗时及距离终点距离。
		Log.i(TAG,"[showStrategy] begin:path="+naviPaths.size());
		if(null == pathIds || pathIds.length<1){
			Log.e(TAG,"[showStrategy]:pathIds error");
			return;
		}
		if(null == naviPaths || !naviPaths.containsKey(pathIds[0])){
			Log.e(TAG,"[showStrategy]:naviPaths error");
			return;
		}

		time_one.setText(changeTime(naviPaths.get(pathIds[0]).getAllTime()));
		distance_one.setText(changeDistance(naviPaths.get(pathIds[0]).getAllLength()));
		if(naviPaths.size()<=2){
			//一条路径
			time_shortest_three.setText("暂无");
			time_three.setText("暂无");
			distance_three.setText("暂无");
			re.findViewById(R.id.methord_three).setEnabled(false);	
		}
		if(naviPaths.size()>=1 && naviPaths.size()<2){
			//两条路径
			time_shortest_two.setText("暂无");
			time_two.setText("暂无");
			distance_two.setText("暂无");
			re.findViewById(R.id.distance_shortest).setEnabled(false);	
		}

		if(naviPaths.size()>=2){
			//显示第三条的内容
			time_shortest_two.setText("方案二");
			time_two.setText(changeTime(naviPaths.get(pathIds[1]).getAllTime()));
			distance_two.setText(changeDistance(naviPaths.get(pathIds[1]).getAllLength()));	
		}
		if(naviPaths.size()>=3){
			//显示第三条的内容
			time_shortest_three.setText("方案三");
			time_three.setText(changeTime(naviPaths.get(pathIds[2]).getAllTime()));
			distance_three.setText(changeDistance(naviPaths.get(pathIds[2]).getAllLength()));	
		}
		roadToll.setText(String.valueOf(naviPaths.get(pathIds[0]).getTollCost()));
		int lights = 0;
		for(int i = 0;i<naviPaths.get(pathIds[0]).getStepsCount();i++){
			lights = lights+naviPaths.get(pathIds[0]).getSteps().get(i).getTrafficLightNumber();
		}
		lightsCount.setText(" 元    红绿灯 "+String.valueOf(lights)+" 个");
		Log.i(TAG,"[showStrategy] end:path="+naviPaths.size());
	}

	private String changeTime(int second){
		if(second <60){
			return String.valueOf(second)+" 秒";
		}else if (second >=3600){
			if(second % 3600 == 0){
				return String.valueOf(second/3600)+" 小时";
			}else{
				return String.valueOf(second/3600)+" 小时"+String.valueOf(second%3600/60)+" 分";	
			}
		}else{
			if(second%60 == 0){
				return String.valueOf(second/60)+" 分钟";
			}else{
				return String.valueOf(second/60)+" 分"+String.valueOf(second%60)+" 秒";
			}
		}
	}
	
	private String changeDistance(int distance) {
		float kilo = ((float) distance) / 1000;
		DecimalFormat format = new DecimalFormat("#.#");
		return String.valueOf(format.format(kilo))+" 公里";
	}
	
	private Handler displayUiHandler = new Handler(Looper.getMainLooper()){
		@Override
		public void handleMessage(Message msg){
			switch (msg.what){
			case 0:
				showStrategy();
				break;
			default:
				break;
			}
		}
	};
}
